package com.dark.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * ClassName: MybatisPlusMeteObjectHandler
 * Description:MybatisPlusMeteObjectHandler
 *
 * @author chengluchao
 * @date: 2022/2/22 14:06
 * @since 1.0
 */
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    private final static String IS_DELETE = "isDelete";
    private final static String VERSION = "version";
    private final static String UPDATE_TIME = "updateTime";
    private final static String CREATE_TIME = "createTime";
    private final static String TS = "ts";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 乐观锁控制
        Object isDelete = getFieldValByName(IS_DELETE, metaObject);
        if (StringUtils.isEmpty(isDelete)) {
            setFieldValByName(IS_DELETE, 0, metaObject);
        }

        // 逻辑删除处理
        Object version = getFieldValByName(VERSION, metaObject);
        if (version == null) {
            setFieldValByName(VERSION, 1, metaObject);
        }

        // 时间处理
        Object createTime = getFieldValByName(CREATE_TIME, metaObject);
        Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
        if (createTime == null || updateTime == null) {
            Date date = new Date();
            if (createTime == null) {
                setFieldValByName(CREATE_TIME, date, metaObject);
            }
            if (updateTime == null) {
                setFieldValByName(UPDATE_TIME, date, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = new Date();
        setFieldValByName(UPDATE_TIME, date, metaObject);
        setFieldValByName(TS, date, metaObject);
    }
}